package com.huonan.component.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@Scope("")
@Slf4j
public class RedisClient {
    private final RedisTemplate<String, String> catchTemplate;

    public RedisClient(RedisTemplate<String, String> catchTemplate) {
        this.catchTemplate = catchTemplate;
    }

    public String getStr(String key) {

        try {
            return catchTemplate.opsForValue().get(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void setStr(String key, String value) {
        try {
            catchTemplate.opsForValue().set(key, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 分布式锁
     * @param lockKey key
     * @param expireTime 实现时间
     * @return 成功返回true
     */
    public boolean lock(String lockKey, Long expireTime) {
        try {
            return Boolean.TRUE.equals(catchTemplate.opsForValue().setIfAbsent(lockKey, "locked", expireTime,
                    TimeUnit.SECONDS));
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 解
     * @param lockKey
     * @return
     */
    public boolean unlock(String lockKey) {
        try {
            return Boolean.TRUE.equals(catchTemplate.delete(lockKey));
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

//    /**
//     * 序列化、反序列化
//     */
//    public String StringSerialize(String value) {
//        RedisSerializer<String> serializer = new RedisSerializer<>();
//        catchTemplate.setStringSerializer(serializer.serialize(value));
//        return null;
//    }
}
